package model

import (
	"air_chat/common/global"
	"errors"

	"gorm.io/gorm"
)

type UserAccount struct {
	CommonModel
	// 根据sql目录下的表结构创建结构体
	Identity string `json:"identity" gorm:"column:identity;size:36;not null" ` // 唯一标识
	Nickname string `json:"nickname" gorm:"column:nickname;size:60;not null" ` // 昵称
	Password string `json:"password" gorm:"column:password;size:60;not null" ` // 密码
	Salt     string `json:"salt" gorm:"column:salt;size:20;not null" `         // 密码盐
	Mobile   string `json:"mobile" gorm:"column:mobile;size:20;not null" `     // 手机号
}

func (*UserAccount) TableName() string {
	return "t_user_account"
}

func CreateUser(user *UserAccount) error {

	var userDb UserAccount
	global.DB.Where("mobile = ?", user.Mobile).First(userDb)
	if userDb.ID > 0 {
		return errors.New("用户已存在")
	}

	return global.DB.Create(user).Error
}

func GetUserList(nickname string) *gorm.DB {
	return global.DB.Model(new(UserAccount)).Omit("password").Where("nickname like ? OR email like ?", "%"+nickname+"%", "%"+nickname+"%")
}

func GetUserModel() *gorm.DB {
	return global.DB.Model(new(UserAccount))
}

func GetUserByMobile(mobile string) (*UserAccount, error) {
	var user UserAccount
	err := global.DB.Where("mobile =? and delete_time is null", mobile).First(&user).Error
	return &user, err
}
